<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/** Customer or user class
 *
 * This is customer class to generate the main page for login and registration
 *
 * @author  Zoms
 * @version 39
 * @copyright copyright (c) 2011, Boston Univeristy Under BSD
 * @todo add function to retrive password
 * @todo add function to update profile
 */
class User extends CI_Controller {

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     * 		http://example.com/index.php/welcome
     * 	- or -  
     * 		http://example.com/index.php/welcome/index
     * 	- or -
     * Since this controller is set as the default controller in 
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see http://codeigniter.com/user_guide/general/urls.html
     */
    function __construct() {
        parent::__construct();
    }

    function index() { // done
         $this->go();
        
    }

     function go() // done
     {
        
        if ($this->session->userdata('c_logged_in') || $this->session->userdata('e_logged_in'))
        { 
             redirect('yogette/member');
        }
        else
        {
                // the user will be redirected in case there is no cockie or failure login
            $this->login();
        } 
     
     }
    
    
    /** Login a User
     *
     *  This function is the main function in this class and will login users to the website and will check if their password and username
     *  validation if yes they will get a message with error and if not they will be registered
     *  after checking their input rules like the size of the password, the validaty of the password 
     *  and hash the password using md5
     *  After they successfully login they will be redirected to the member main page and created a session with a cockie 
     *
     *  
     */
    function login() { //done
        // this rules checks the username and password validaty and inforce user to eneter both 
        $this->form_validation->set_rules('username', 'Username', 'required|trim|max_length[50]|min_length[4]|xss_clean');
        $this->form_validation->set_rules('password', 'Password', 'required|trim|max_length[200]|min_length[6]|xss_clean|md5');

        // check the validation of the filled form and for the first time logins and if it is false the user will be viewing  to login page
        // and if TRUE thier inputs will be accepted and check with the DB
        if ($this->form_validation->run() == FALSE) {
            // loading the viewing page for the user 
            $this->load->view('view_login');
         } else {
            // processes their input login the user
            extract($_POST);
               
            //check the username and password which we got from the login form to the DB and get the customer ID
            $array = $this->model_user->model_authenticate($username, $password);
            
            $cus_id=false;
            $emp_id=false;
            if ($array != FALSE && $array['type'] == 1)
            {
                  $cus_id = $array['cus_id'];
                  $cus_email = $array['cus_email'];
                  $cus_username =  $array['cus_username'];     
            }
            if ($array != FALSE && $array['type'] == 2)
            {
                  $emp_id = $array['emp_id'];
                  $emp_email = $array['emp_email'];
                  $emp_username =  $array['emp_username'];     
            }
            // check the customer ID if it is valid or not and if it is valid the user will get a cockie and logged in the member main page or if it is not valid
            // the session will put login error trigger
            if (!$cus_id || !$cus_email || !$cus_username) 
            {
               
                if (!$emp_id || !$emp_email || !$emp_username)
                {
                    // create a session with a login error so this user will not be able to access the member login page and post the error to his page
                    $this->session->set_flashdata('login_error', TRUE);
                    //the user will be redirected back to the login page
                    redirect('yogette/user/login');
                }
                else
                {
                    // the cockie with session will be created with the customer ID and a login TRUE	
                    $this->session->set_userdata(array(
                        'e_logged_in' => TRUE,
                        'c_logged_in' => FALSE,
                        'emp_id' => $emp_id,
                        'emp_email'=>$emp_email,
                        'emp_username'=>$emp_username
                    ));
                    // the customer will be redirected to the member main page
                    redirect('yogette/member');

                }
            }  
            else 
            {

                // the cockie with session will be created with the customer ID and a login TRUE	
                $this->session->set_userdata(array(
                    'c_logged_in' => TRUE,
                    'e_logged_in' => FALSE,
                    'cus_id' => $cus_id,
                    'cus_email'=>$cus_email,
                    'cus_username'=>$cus_username
                ));
                // the customer will be redirected to the member main page
                redirect('yogette/member');
                     
            }
          
        }
    }

    /** Register a new customer
     *
     *  This function will register new customers to the website and will check if their email and username
     *  are already in the DB if yes they will get a message with error and if not they will be registered
     *  after checking their input rules like the size of the password, the validaty of the email 
     *  also checks the confirmation password
     *  After they successfully register they will be redirected to the loging page
     *
     *  @todo - must take out the city and the state out of the form
     *  @todo	- must add credit card information for the customer
     *  @todo - add the functionality to check if the member is suspened for payment will not be directed to the member page
     *  	
     */
    function register_user() { // done

        $this->load->model('Model_register', 'register');

        $countries['array'] = $this->register->get_all_countries();
        
        // this rule to check the username validaty "username is required maximum length is 50 charecter minimum length is 4 lowered case and checked if in DB adn cleaned by xss filters" 
        $this->form_validation->set_rules('username', 'Username', 'required|trim|max_length[50]|min_length[4]|alpha_numeric|strtolower|callback_username_not_exists|xss_clean');
        $this->form_validation->set_rules('first_name', 'First name', 'required|trim|max_length[50]|xss_clean');
        $this->form_validation->set_rules('last_name', 'Last name', 'required|trim|max_length[50]|xss_clean');
        $this->form_validation->set_rules('dob', 'Dob', 'required|valid_date|exact_length[10]');
        $this->form_validation->set_rules('email', 'Email', 'required|trim|xss_clean|max_length[100]|valid_email|strtolower|callback_email_not_exists');
        
        $this->form_validation->set_rules('paypal', 'Paypal', 'trim|xss_clean|max_length[20]|min_length[4]|strtolower|callback_paypal_not_exists');
        $this->form_validation->set_rules('password', 'Password', 'required|trim|max_length[200]|min_length[6]|xss_clean|matches[password_confirm]|md5');
        $this->form_validation->set_rules('password_confirm', 'Password confirm', 'required|trim|max_length[200]|min_length[6]|xss_clean|md5');
        $this->form_validation->set_rules('shipaddress', 'Ship Address', 'required|trim|max_length[200]|xss_clean');
        $this->form_validation->set_rules('billaddress', 'Bill Address', 'required|trim|max_length[200]|xss_clean');
        $this->form_validation->set_rules('credit_card_type', 'Credit Card Type', 'required|trim|xss_clean');//callback_alpha_visa|callback_alpha_master|callback_alpha_american|callback_alpha_discover|callback_alpha_jcb|callback_alpha_diner
        $this->form_validation->set_rules('credit_card_number', 'Credit Card Number', 'required|exact_length[16]|trim|is_natural_no_zero|xss_clean|callback_credit_not_exists|callback_alpha_all');//callback_alpha_dash
        $this->form_validation->set_rules('credit_card_year', 'Credit Card Year', 'required|trim|xss_clean');
        $this->form_validation->set_rules('credit_card_month', 'Credit Card Month', 'required|trim|xss_clean');
        $this->form_validation->set_rules('credit_card_cvv', 'Credit Card CVV', 'required|trim|exact_length[3]|is_natural_no_zero|xss_clean');
        
        $this->form_validation->set_rules('countryname', 'country choose', 'required');
    if ($this->form_validation->run() == FALSE) {
            // viewing the registration page to the user  
            $this->load->view('view_register', $countries);
        } else {
            // posting all inputs to the variables  after successful validation for these inputs
            $username = $this->input->post('username');
            $first_name = $this->input->post('first_name');
            $last_name = $this->input->post('last_name');
            $dob = $this->input->post('dob');
            $email = $this->input->post('email');
            $password = $this->input->post('password');
            $shipaddress = $this->input->post('shipaddress');
            $billaddress = $this->input->post('billaddress');
            $countryname = $this->input->post('countryname');
            $credit_card_type = $this->input->post('credit_card_type');
            $credit_card_number = $this->input->post('credit_card_number');
            $credit_card_month = $this->input->post('credit_card_month');
            $credit_card_year = $this->input->post('credit_card_year');
            $credit_card_cvv = $this->input->post('credit_card_cvv');
            $paypal = $this->input->post('paypal');

           // $encrypted_username = $this->encrypt->encode($username);
            $encrypted_shipaddress = $this->encrypt->encode($shipaddress);
            $encrypted_billaddress = $this->encrypt->encode($billaddress);
            $encrypted_credit_card_cvv = $this->encrypt->encode($credit_card_cvv);
            $encrypted_credit_card_number = $this->encrypt->encode($credit_card_number);
            
            // adding the user to the database after calling the model for that
        if ($encrypted_credit_card_number != null){
            if ($this->model_register->model_add_user($username,  
                    $password, $first_name, $last_name, $dob, $email, $encrypted_shipaddress, 
                    $encrypted_billaddress, $countryname, $credit_card_type, $encrypted_credit_card_number, 
                    $credit_card_month, $credit_card_year, $encrypted_credit_card_cvv, $paypal)) 
                {
                    // redirect the user to the main loging page after successful addition
                    redirect('user/login');
        } else {
            redirect('user/register_user');       
        }
        }
      
        }
    }

  
  /*  function alpha_dash($credit_card_number)
   {
        $this->form_validation->set_message('alpha_dash', 'This %s Is Not Valid. please use another Card');
        
        if (!preg_match("^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})^", $credit_card_number))
        {
            return false;
        } else {
            return true;
        }
    }*/
    
    

   function alpha_all($credit_card_number)
   {
       $credit_card_type = $this->input->post('credit_card_type');

       if ($credit_card_type == "VISA"){ 
           $this->form_validation->set_message('alpha_all', 'This %s Is Not a Valid VISA. please use another Card');
        
        if (!preg_match("^4[0-9]{12}(?:[0-9]{3})?^", $credit_card_number))
        {
            return false;
        } else {
            return true;
        }
        
       }
       
        if ($credit_card_type == 'MasterCard'){ 
        $this->form_validation->set_message('alpha_all', 'This %s Is Not a Valid MasterCard. please use another Card');
        
        if (!preg_match("^5[1-5][0-9]{14}^", $credit_card_number))
        {
            return false;
        } else {
            return true;
        }
      }
       
       
       if ($credit_card_type == 'AmericanExpress'){ 
        $this->form_validation->set_message('alpha_all', 'This %s Is Not a Valid AmericanExpress. please use another Card');
        
        if (!preg_match("^3[47][0-9]{13}^", $credit_card_number))
        {
            return false;
        } else {
            return true;
        }
       }
       
        if ($credit_card_type == 'DinersClub'){ 
        $this->form_validation->set_message('alpha_all', 'This %s Is Not a Valid Diners Club. please use another Card');
        
        if (!preg_match("^3(?:0[0-5]|[68][0-9])[0-9]{11}^", $credit_card_number))
        {
            return false;
        } else {
            return true;
        }
        }
        
         if ($credit_card_type == 'Discover'){ 
        $this->form_validation->set_message('alpha_all', 'This %s Is Not a Valid Discover. please use another Card');
        
        if (!preg_match("^6(?:011|5[0-9]{2})[0-9]{12}^", $credit_card_number))
        {
            return false;
        } else {
            return true;
        }
        }
        else if ($credit_card_type == 'JCB'){
            $this->form_validation->set_message('alpha_all', 'This %s Is Not a Valid JCB. please use another Card');
        
        if (!preg_match("^(?:2131|1800|35\d{3})\d{11}^", $credit_card_number))
        {
            return false;
        } else {
            return true;
        }
        
        }
        else{
           $this->form_validation->set_message('alpha_all', 'Error %s We don not have this type. please check ');
            return false;
        }
    }
    
 
   
    
     function special_order()
        {
            if ($this->session->userdata('e_logged_in'))
            {
                $emp_id = $this->session->userdata('emp_id');
                $search_table['items'] = FALSE;
                $search_table['flag'] = FALSE;
                $this->load->view('view_search_special',$search_table);
            }
            else
            {
                // the user will be redirected in case there is no cockie or failure login
		redirect('yogette/user/login');
            }
        }
        
    function search_specials() 
	{
               
		// this rule to check the search field validaty as required 
		$this->form_validation->set_rules('search_field', 'Search field', 'required|trim|max_length[50]|min_length[4]|alpha_numeric|strtolower|callback_username_exists|xss_clean');
		// check the validation of the filled form  if it is false the user will be viewing  to search field again
		if ($this->form_validation->run() == FALSE)
		{
                        $search_table['items'] = FALSE;
			//loading the view of search field 
                        $search_table['flag'] = FALSE;
			$this->load->view('view_search_special', $search_table);
		}
		else
		{
			//processes their input login the user
			extract($_POST);
			
			// get the search array result from the seearch model from the DB by supplying the dvd type (games or movies) and the search field
			$search_results = $this->model_search->search_special($search_field);
			
			// run another function to generate the table and output to the member the list result by providing the search array result from the DB and and the dvd type either movie or game 
			//$this->search_specials_list($search_results);
                        
                        $search_table['items'] = $search_results;
                        $search_table['flag'] = TRUE;
                        $this->load->view('view_search_special',$search_table);
		}	
	}
        
        function shipped_order() 
	{
               
		// this rule to check the search field validaty as required 
		$this->form_validation->set_rules('search_field', 'Search field', 'required|trim|max_length[50]|min_length[4]|alpha_numeric|strtolower|callback_username_exists|xss_clean');
		// check the validation of the filled form  if it is false the user will be viewing  to search field again
		if ($this->form_validation->run() == FALSE)
		{
                        $search_table['items'] = FALSE;
			//loading the view of search field 
                       // $search_table['flag'] = FALSE;
			$this->load->view('view_shipped_order', $search_table);
		}
		else
		{
			//processes their input login the user
			extract($_POST);
			
			// get the search array result from the seearch model from the DB by supplying the dvd type (games or movies) and the search field
			$search_results = $this->model_search->search_shipped_orders($search_field);
			
			// run another function to generate the table and output to the member the list result by providing the search array result from the DB and and the dvd type either movie or game 
			//$this->search_specials_list($search_results);
                        
                        $search_table['items'] = $search_results;
                       // $search_table['flag'] = TRUE;
                        $this->load->view('view_shipped_order',$search_table);
		}	
	}
        
        
         function search_reservation() 
	{
               
		// this rule to check the search field validaty as required 
		$this->form_validation->set_rules('search_field', 'Search field', 'required|trim|max_length[50]|min_length[4]|alpha_numeric|strtolower|callback_username_exists|xss_clean');
		// check the validation of the filled form  if it is false the user will be viewing  to search field again
		if ($this->form_validation->run() == FALSE)
		{
                        $search_table['items'] = FALSE;
			//loading the view of search field 
                       // $search_table['flag'] = FALSE;
			$this->load->view('view_emp_reservation', $search_table);
		}
		else
		{
			//processes their input login the user
			extract($_POST);
			
			// get the search array result from the seearch model from the DB by supplying the dvd type (games or movies) and the search field
			$search_results = $this->model_search->search_customer_reservation($search_field);
			
			// run another function to generate the table and output to the member the list result by providing the search array result from the DB and and the dvd type either movie or game 
			//$this->search_specials_list($search_results);
                        
                        $search_table['items'] = $search_results;
                       // $search_table['flag'] = TRUE;
                        $this->load->view('view_emp_reservation',$search_table);
		}	
	}
        
        function search_specials_list($search_results)
	{
		
            // assign to the search table the dvd type to be 1 "movie" so passing this variable will help to indicate the type of results either movies or games
           // $search_table['dvd_type'] = 1;

            // check if the array of results is not empty before gemerating the table to be able to print the proper error
            //if it is empty will assign FALSE for both games and movies 
            if ($search_results != FALSE)
            {
                    // clearing the table from any values to be sure that it is empty before adding the inputs
                    $this->table->clear();

                    // add Null to the empty culomns
                    $this->table->set_empty("&nbsp;");

                    // adding the heading of the table to be specific for movies
                    $this->table->set_heading('Order ID', 'Customer ID', 'Product ID', 'Store Location ID', 'Special Description', 'Order Date', 'Click to Process');

                    // run a for loop for each row in the result array to add the link to add a specific movie from the resulted array to the queue
                    foreach ($search_results as $search_results)
                    {
                            //adding all required fields in addition to the add link to the queue
                            $this->table->add_row($search_results['order_id'], $search_results['cus_id'], 
                            $search_results['prod_id'], $search_results['store_loc_id'], $search_results['special_desc'], 
                            $search_results['order_date'], anchor('cart/emp_checkout'.$search_results['order_id']. '/' .$search_results['cus_id'],'Add', array('class' => 'add')));
                    }

                    // generate the table with all required fields for movies
                    $search_table['items'] = $this->table->generate();
            }
            else
            {
                    // assigning False to both movies and games arrays to provide the proper error
                    $search_table['items'] = FALSE;

            }

           

            // view the search field again after getting the results so the customer can search again if he/she does not want to add this movie or game to the queue
            $this->load->view('view_search_special',$search_table);
            
             // view the the both searching results tables for either movies or games by passing the generated search table arrays with the dvd type inside this array 
            //$this->load->view('view_search_special_results',$search_table);

	}
        
        
        function view_blocked() 
	{
               
            if ($this->session->userdata('e_logged_in'))
            {  // get the search array result from the seearch model from the DB by supplying the dvd type (games or movies) and the search field
                //$search_results = $this->model_search->search_blocked();

                // run another function to generate the table and output to the member the list result by providing the search array result from the DB and and the dvd type either movie or game 
                //$this->search_specials_list($search_results);

                $search_table['items'] = $this->model_search->search_blocked();
                
                $this->load->view('view_search_blocked',$search_table);
		}
            else
            {
                // the user will be redirected in case there is no cockie or failure login
		redirect('yogette/user/login');
            }	
	}
        
        
        function block_customer() 
	{
               
            if ($this->session->userdata('e_logged_in'))
            {  // get the search array result from the seearch model from the DB by supplying the dvd type (games or movies) and the search field
                //$search_results = $this->model_search->search_customers_to_block();

                // run another function to generate the table and output to the member the list result by providing the search array result from the DB and and the dvd type either movie or game 
                //$this->search_specials_list($search_results);

                $search_table['items'] = $this->model_search->search_customers_to_block();
                
                $this->load->view('view_customer_block',$search_table);
		}
            else
            {
                // the user will be redirected in case there is no cockie or failure login
		redirect('yogette/user/login');
            }	
	}
        
        
        function hold()
        {
            if ($this->session->userdata('e_logged_in'))
            { 
                $cus_id = $this->uri->segment(3);
                $result = $this->model_user->block_customer($cus_id);
                
                if ($result)
                    {
                        $this->block_customer();
                    }
                    else
                    {
                          redirect('yogette/error');
                    }
            }
            else
            {
                // the user will be redirected in case there is no cockie or failure login
		redirect('yogette/user/login');
            }	
        }
        
        
        function unhold()
        {
            if ($this->session->userdata('e_logged_in'))
            { 
                $cus_id = $this->uri->segment(3);
                $result = $this->model_user->un_block_customer($cus_id);
                
                if ($result)
                    {
                        $this->view_blocked();
                    }
                    else
                    {
                          redirect('yogette/error');
                    }
            }
            else
            {
                // the user will be redirected in case there is no cockie or failure login
		redirect('yogette/user/login');
            }	
        }
        
        
     function update_user() 
     { //done
        if ($this->session->userdata('c_logged_in'))
         {
            $this->load->model('Model_register', 'register');
            $cus_id = $this->session->userdata('cus_id');       
            $member['array'] = $this->register->get_all_countries();
            //$this->load->view('view_register', $countries);
            $member['query'] = $this->model_user->get_member_info($cus_id);
            // this rule to check the username validaty "username is required maximum length is 50 charecter minimum length is 4 lowered case and checked if in DB adn cleaned by xss filters" 
            //$this->form_validation->set_rules('username', 'Username', 'required|trim|max_length[50]|min_length[4]|alpha_numeric|strtolower|callback_username_not_exists|xss_clean');
            // this rules checks the first_name validaty "first name is required, maximum length 50 cleaned by xss filter "
            $this->form_validation->set_rules('first_name', 'First name', 'required|trim|max_length[50]|xss_clean');
            // this rules checks the last_name validaty "last name is required, maximum length 50 cleaned by xss filter "
            $this->form_validation->set_rules('last_name', 'Last name', 'required|trim|max_length[50]|xss_clean');
            // this rules checks the email validaty "email is required, maximum length 100 cleaned by xss filter, lowerd case and checked that it does not exist in DB, and it is a valid email"
            $this->form_validation->set_rules('dob', 'Dob', 'required|valid_date|exact_length[10]');
            $this->form_validation->set_rules('email', 'Email', 'required|trim|xss_clean|max_length[100]|valid_email|strtolower|callback_email_exists');

           // $this->form_validation->set_rules('paypal', 'Paypal', 'required|trim|max_length[50]|min_length[4]|alpha_numeric|strtolower|callback_paypal_not_exists|xss_clean');
            $this->form_validation->set_rules('paypal', 'Paypal', 'trim|xss_clean|max_length[20]|min_length[4]|strtolower|callback_paypal_exists');
            // this rules checks the password validaty "password is required, maximum length 200 cleaned by xss filter, hashed using md5 and matched with the password confirm field"
            //$this->form_validation->set_rules('password', 'Password', 'required|trim|max_length[200]|min_length[6]|xss_clean|matches[password_confirm]|md5');
            // this rules checks the password confirm validaty "password is required, maximum length 200 cleaned by xss filter" 
            //$this->form_validation->set_rules('password_confirm', 'Password confirm', 'required|trim|max_length[200]|min_length[6]|xss_clean');
            // this rules checks the address validaty "address is required, maximum length 200 cleaned by xss filter"
            $this->form_validation->set_rules('shipaddress', 'Ship Address', 'required|trim|max_length[200]|xss_clean');
            $this->form_validation->set_rules('billaddress', 'Bill Address', 'required|trim|max_length[200]|xss_clean');
            // this rules checks the zip code validaty "zipcode is required, maximum length 6 cleaned by xss filter and is numerical and not zero"
            //$this->form_validation->set_rules('zipcode', 'Zip code', 'required|trim|max_length[6]|is_natural_no_zero|xss_clean');
            // this rules checks the zip code validaty "zipcode is required, maximum length 6 cleaned by xss filter and is numerical and not zero"
            $this->form_validation->set_rules('credit_card_type', 'Credit Card Type', 'required|trim|xss_clean');
            $this->form_validation->set_rules('credit_card_number', 'Credit Card Number', 'required|exact_length[16]|trim|is_natural_no_zero|xss_clean|callback_credit_exists|callback_alpha_all');
            $this->form_validation->set_rules('credit_card_year', 'Credit Card Year', 'required|trim|xss_clean');
            $this->form_validation->set_rules('credit_card_month', 'Credit Card Month', 'required|trim|xss_clean');
            $this->form_validation->set_rules('credit_card_cvv', 'Credit Card CVV', 'required|trim|exact_length[3]|is_natural_no_zero|xss_clean');

            
            $this->form_validation->set_rules('countryname', 'country choose', 'required');
             
        if ($this->form_validation->run() == FALSE) {
            // viewing the registration page to the user  
            $this->load->view('view_edit_member_info', $member );
           
        } else {
            // posting all inputs to the variables  after successful validation for these inputs
      
            $first_name = $this->input->post('first_name');
            $last_name = $this->input->post('last_name');
            $dob = $this->input->post('dob');
            $email = $this->input->post('email');
            $shipaddress = $this->input->post('shipaddress');
            $billaddress = $this->input->post('billaddress');
            $countryname = $this->input->post('countryname');
            $credit_card_type = $this->input->post('credit_card_type');
            $credit_card_number = $this->input->post('credit_card_number');
            $credit_card_month = $this->input->post('credit_card_month');
            $credit_card_year = $this->input->post('credit_card_year');
            $credit_card_cvv = $this->input->post('credit_card_cvv');
            $paypal = $this->input->post('paypal');
          
            $encrypted_shipaddress = $this->encrypt->encode($shipaddress);
            $encrypted_billaddress = $this->encrypt->encode($billaddress);
            $encrypted_credit_card_number = $this->encrypt->encode($credit_card_number);
            $encrypted_credit_card_cvv = $this->encrypt->encode($credit_card_cvv);
            
            // adding the user to the database after calling the model for that
            //if ($countryid != null){
            if ($encrypted_credit_card_number != null){
                if ($this->model_user->model_update_user($cus_id,$first_name, $last_name, 
                    $dob, $email, $encrypted_shipaddress,$encrypted_billaddress, $countryname, 
                    $credit_card_type, $encrypted_credit_card_number,$credit_card_month, $credit_card_year, 
                    $encrypted_credit_card_cvv, $paypal)) 
                    {
                       
                        redirect('yogette/member');
                    } 
                else 
                    {
                        redirect('yogette/user/update_user');       
                    }  
                }
            }
        }
        else
        {
            redirect('yogette/user');
        }
    }
    
    
    
     function update_emp() 
    { //done

    if ($this->session->userdata('e_logged_in'))
        {
            $this->load->model('Model_register', 'register');
            $emp_id = $this->session->userdata('emp_id');       
            $employee['array'] = $this->register->get_all_countries();
           
            $employee['query'] = $this->model_user->get_employee_only_info($emp_id);
            $this->form_validation->set_rules('first_name', 'First name', 'required|trim|max_length[50]|xss_clean');
            $this->form_validation->set_rules('last_name', 'Last name', 'required|trim|max_length[50]|xss_clean');
            $this->form_validation->set_rules('dob', 'Dob', 'required|valid_date|exact_length[10]');
            $this->form_validation->set_rules('email', 'Email', 'required|trim|xss_clean|max_length[100]|valid_email|strtolower|callback_email_exists');

           $this->form_validation->set_rules('address', 'Address', 'required|trim|max_length[200]|xss_clean|md5');
            if ($this->form_validation->run() == FALSE) {
            // viewing the registration page to the user  
            $this->load->view('view_edit_employee_info', $employee );
           
        } else {
            // posting all inputs to the variables  after successful validation for these inputs
      
            $first_name = $this->input->post('first_name');
            $last_name = $this->input->post('last_name');
            $dob = $this->input->post('dob');
            $email = $this->input->post('email');
            //$shipaddress = $this->input->post('shipaddress');
            $address = $this->input->post('address');
            $countryname = $this->input->post('countryname');
            
            
            $encrypted_address = $this->encrypt->encode($address);
           
            
              //  $md5_address = md5($address);
              
            // adding the user to the database after calling the model for that
            //if ($countryid != null){
            if ($this->model_user->model_update_employee($emp_id,$first_name, $last_name, 
                    $dob, $email, $encrypted_address, $countryname)) 
                    {
                        redirect('yogette/member');
                    }
                else 
                    {
                       // redirect('yogette/user/update_user');       
                    }  
                }
        }
        else
        {
           
            redirect('yogette/user');
        }
    }
    
    /** Check if username does not exist
     *
     *  This function will check if the username does not exist in the databse and create a rule to be used in the validation form for the username 
     *  as a callback 
     *
     *  @param varchar $username This parameter will be input to the function for checking it in the DB
     *  @return binary The function will return false if the the username does not exist in the DB and true if it exists
     */
    function username_not_exists($username) { //done
        // this request to set a message for validation for the user in case if the username already exists in DB 
        $this->form_validation->set_message('username_not_exists', 'This %s already exist. please use another username');

        // call the model to check the existanse of the username and if it is there the return will be false 
        if ($this->model_register->check_exist_username($username)) {
            return false;
        } else {
            return true;
        }
    }

     function username_exists($username) { //done
        // this request to set a message for validation for the user in case if the username already exists in DB 
        $this->form_validation->set_message('username_exists', 'This %s not exist. please check username entered');

        // call the model to check the existanse of the username and if it is there the return will be false 
        if ($this->model_register->check_exist_username($username)) {
            return true;
        } else {
            return false;
        }
    }
    /** Check if email does not exist
     *
     *  This function will check if the email does not exist in the databse and create a rule to be used in the validation form for the email 
     *  as a callback 
     *
     *  @param varchar $email This parameter will be input to the function for checking it in the DB
     *  @return binary The function will return false if the the email does not exist in the DB and true if it exists
     */
    function email_not_exists($email) { //done
        // this request to set a message for validation for the user in case if the email already exists in DB 
        $this->form_validation->set_message('email_not_exists', 'This %s is already registered');

        // call the model to check the existanse of the email and if it is there the return will be false
        if ($this->model_register->check_exist_email($email)) {
            return false;
        } else {
            return true;
        }
    }

    
    function credit_not_exists($credit_card_number) {//done
        // this request to set a message for validation for the user in case if the email already exists in DB 
        $this->form_validation->set_message('creditCard_not_exists', 'This %s is already registered');

        // call the model to check the existanse of the email and if it is there the return will be false
        if ($this->model_register->check_exist_credit($credit_card_number)) {
            return false;
        } else {
            return true;
        }
    }
    
    function paypal_not_exists($paypal) {//done
        // this request to set a message for validation for the user in case if the email already exists in DB 
        $this->form_validation->set_message('paypal_not_exists', 'This %s is already registered');

        // call the model to check the existanse of the email and if it is there the return will be false
        if ($this->model_register->check_exist_paypal($paypal)) {
            return false;
        } else {
            return true;
        }
    }
    
    function paypal_exists($paypal) {//done
        // this request to set a message for validation for the user in case if the email already exists in DB 
        $this->form_validation->set_message('paypal_exists', 'This %s is already registered');
        $cus_id = $this->session->userdata('cus_id'); 
        // call the model to check the existanse of the email and if it is there the return will be false
        if ($this->model_user->check_exist_paypal($cus_id,$paypal)) {
            return false;
        } else {
            return true;
        }
    }
    
    function credit_exists($credit_card_number) {//done
        // this request to set a message for validation for the user in case if the email already exists in DB 
        $this->form_validation->set_message('credit_exists', 'This %s is already registered');
        $cus_id = $this->session->userdata('cus_id'); 
        // call the model to check the existanse of the email and if it is there the return will be false
        if ($this->model_user->check_exist_credit($cus_id ,$credit_card_number)) {
            return false;
        } else {
            return true;
        }
    }
    
    function email_exists($email) {//done
        // this request to set a message for validation for the user in case if the email already exists in DB 
        $this->form_validation->set_message('email_exists', 'This %s is not registered');

        // call the model to check the existanse of the email and if it is there the return will be false
        if ($this->model_register->check_exist_email($email)) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    function reset_password() {//done
        // this rules checks the email validaty "email is required, maximum length 100 cleaned by xss filter, lowerd case and checked that it does not exist in DB, and it is a valid email"
        $this->form_validation->set_rules('email', 'email', 'required|trim|xss_clean|max_length[100]|valid_email|strtolower|callback_email_exists');

        // check the validation of the filled form and for the first time registering and if it is false the user will be viewing  to registeration page
        if ($this->form_validation->run() == FALSE) {
            // viewing the registration page to the user  
            $this->load->view('view_reset_password');
        } else {
            // posting all inputs to the variables  after successful validation for these inputs

            $email = $this->input->post('email');

            // generate password with 8 charecters
            $password = $this->generate_password(8);

            $md5_password = md5($password);

            // adding the user to the database after calling the model for that
            $this->model_register->model_reset_password($email, $md5_password, $password);

            // redirect the user to the main loging page after successful addition
            redirect('user/login');
        }
    }

    function generate_password($length = 8) {//done

        // start with a blank password
        $password = "";

        // define possible characters - any character in this string can be
        // picked for use in the password, so if you want to put vowels back in
        // or add special characters such as exclamation marks, this is where
        // you should do it
        $possible = "2346789bcdfghjkmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ";

        // we refer to the length of $possible a few times, so let's grab it now
        $maxlength = strlen($possible);

        // check for length overflow and truncate if necessary
        if ($length > $maxlength) {
            $length = $maxlength;
        }

        // set up a counter for how many characters are in the password so far
        $i = 0;

        // add random characters to $password until $length is reached
        while ($i < $length) {

            // pick a random character from the possible ones
            $char = substr($possible, mt_rand(0, $maxlength - 1), 1);

            // have we already used this character in $password?
            if (!strstr($password, $char)) {
                // no, so it's OK to add it onto the end of whatever we've already got...
                $password .= $char;
                // ... and increase the counter by one
                $i++;
            }
        }

        // done!
        return $password;
    }

    
    function submit_payment()
    {
       if ($this->session->userdata('c_logged_in'))
        {
           $cus_id = $this->session->userdata('cus_id');
           $cus_email = $this->session->userdata('cus_email');
           // Update finsihed for reservation flag and insert in history
           $total = $this->input->post('totalhidden');
            
           $res_queue['reserv'] = $this->model_reserve->get_my_reservations($cus_id);
           
           if ($res_queue['reserv'])
           {
               $result = $this->model_reserve->paid_reservation($cus_id , $res_queue);
           }
           
           $cart_queue = $this->model_cart->get_cart($cus_id);
           //$res_queue['items'] = $this->model_cart->get_cart($cus_id);
           if ($cart_queue != FALSE)//$res_queue['items']
           {
               // adding libility
               $res_queue['items'] = $cart_queue->result();
               $result = $this->model_user->paid_cart($cus_id , $cus_email , $total , $res_queue);
           }
           else
            {
               // assign FALSE the movies array so the code can distinguish between if we have table or not and print the error if not
               $res_queue['items'] = FALSE;
            }
            
            $result2 = $this->model_user->add_libility($cus_id , $total);
           if ($result && $result2)
               {
                   redirect('yogette/member');
               }
               else
               {
                   redirect('yogette/error');
             
               }
         }
        else
        {
            redirect('yogette/user');
        }
        
        
    }
    function logout()//done
	{
		/* to destroy the seesion and logout*/
		$this->session->sess_destroy();
                redirect('user');
	}
}